<template>
  <a-card :bordered='false'>
    <!-- 查询区域 -->
    <search ref='search' :config='searchConfig' @search='search' @getHeight='getHeight' />

    <!-- table区域-begin -->
    <div class='page_table'>
      <vxe-grid
        ref='xGrid'
        v-bind='vexConfig'
        :align='left'
        :border='true'
        :checkbox-config='checkboxConfig'
        :columns='columns'
        :data='dataSource'
        :height='pageHeight-seachHeight-94'
        :loading='loading'
        :resizable='true'
        :showOverflow='true'
        :toolbar-config='tableToolbar'
        size='mini'
        @checkbox-change='selectChangeEvent'
        @checkbox-all='selectChangeEvent'
      >
        <template #toolbar_buttons>
          <div class="flex" style="display: flex;justify-content: space-between;align-items: center">
          <!-- 操作按钮区域 -->
          <div class='table-operator'>
            <a-button type='primary' @click="downExportXls('tpm_act_execute_sales_service')">导出</a-button>
          </div>
<!--          <div style='display: flex;gap: 30px;align-items: center'>-->
<!--            <span style='fontWeight:700'>总销售额:</span>-->
<!--            <span style='margin:12px 0'>当页合计: {{ moneyData.pagePriceAmount || '暂无' }}</span>-->
<!--            <span>总合计:{{ moneyData.totalAmount || '暂无' }}</span>-->
<!--          </div>-->
          </div>
        </template>
        <template #actCode='{ row,rowIndex }'>
          <a @click='handleEdit(row)'>{{ row.actCode }}</a>
        </template>
        <template #pager>
          <vxe-pager
            :currentPage.sync='ipagination.current'
            :layouts="['Total', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump','Sizes', 'FullJump']"
            :page-size.sync='ipagination.pageSize'
            :pageSizes='ipagination.pageSizeOptions'
            :total='ipagination.total'
            @page-change='handlePageChange'>
          </vxe-pager>
        </template>
      </vxe-grid>
    </div>
    <!-- table区域-end -->

    <salesDetailModal ref='modalForm' @ok='modalFormOk'></salesDetailModal>
  </a-card>
</template>

<script>
import { PageListMixin } from '@/mixins/PageListMixin'
import { getAction, postAction } from '@api/manage'
import salesDetailModal from '@/views/tmr/costCenter/modules/salesDetailModal'
import HpayselectCom from '@/components/cn-components/HpayselectCom'
import pick from 'lodash.pick'

export default {
  name: 'salesDetailsReport',
  description: '活动销量明细报表',
  mixins: [PageListMixin],
  components: {
    salesDetailModal,
    HpayselectCom
  },
  data() {
    return {
      permflag:'tpm_act_exec_sales_impl',
      loading: false,
      searchConfig: [
        {
          type: 'input',
          name: 'actCode',
          placeholder: '活动编码',
        },
        {
          type: 'input',
          name: 'actName',
          placeholder: '活动名称'
        },
        {
          type: 'input',
          name: 'terminalCode',
          placeholder: '终端编码'
        },
        {
          type: 'input',
          name: 'terminalName',
          placeholder: '终端名称'
        },
        {
          type: 'input',
          name: 'custCode',
          placeholder: '经销商编码'
        },
        {
          type: 'input',
          name: 'custName',
          placeholder: '经销商名称'
        },
        {
          // label:'售达方编码',
          type: 'date-range',
          name: 'kunnr',
          range: ['submitStartDate', 'submitEndDate'],// 后台接受字段
          placeholder: ['开始时间', '结束时间']
        },
        {
          type: 'tree-select',
          placeholder: '组织',
          dataType: 'org',
          name: 'orgCode'  // 后台接受字段
        },
      ],
      // 表头
      columns: [
        { type: 'checkbox', width: 50, fixed: null ,field: 'a',},
        {
          title: '活动编码',
          minWidth:80,
          field: 'actCode',
          slots: { default: 'actCode' },
        },
        {
          title: '活动名称',
          minWidth:80,
          field: 'actName'
        },
        {
          title: '终端编码',
          minWidth:80,
          field: 'terminalCode'

        },
        {
          title: '终端编码名称',
          minWidth:120,
          field: 'terminalName'
        },
        {
          title: '经销商编码',
          minWidth:100,
          field: 'custCode'
        },
        {
          title: '经销商编码名称',
          minWidth:140,
          field: 'custName'
        },
        {
          title: '销售数量',
          minWidth:80,
          field: 'num'
        },
        {
          title: '总销售金额',
          minWidth:100,
          field: 'priceAmount'
        },
        {
          title: '数据提交时间',
          minWidth:120,
          field: 'createTime',
        },
        {
          title: '执行人',
          minWidth:80,
          field: 'createName'
        },
        {
          title: '执行人职位',
          minWidth:100,
          field: 'positionName'
        },
        {
          title: '执行人所在组织',
          minWidth:140,
          field: 'orgName'
        },
      ],
      url: {
        list: window._CONFIG['domianTpmURL'] + '/tpmActExecuteSalesStatement/findPageListStatement',
        check:window._CONFIG['domianTpmURL'] + 'report/tpmActExecuteReport/examineReport',
        detail: window._CONFIG['domianTpmURL'] + '/tpmActExecuteSalesStatement/statementInfo',

        exportXlsUrl: window._CONFIG['domianTpmURL'] + 'budget/tpmBudgetFee/exportXls',
        closeOne: window._CONFIG['domianTpmURL'] + '/activity/closeActivity',
        deleteBatch: window._CONFIG['domianTpmURL'] + '/activity/delete'
      },
      moneyData:{},
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 10,
        pageSizeOptions: ['10', '20', '30', '40', '50'],
        showTotal: (total, range) => {
          return range[0] + "-" + range[1] + " 共" + total + "条"
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
    }
  },
  methods: {
    handleEdit: async function (record) {
      if (this.url.detail) {
        const res = await getAction(this.url.detail, {id: record.executeDetailId})
        if (res && res.result) {
          record = res.result
        }else{
          this.$message.error(res.message)
        }
      }
      this.$refs.modalForm.edit(record);
      this.$refs.modalForm.title = " ";
    },
    loadData(arg) {
      if (!this.url || !this.url.list) {
        // this.$message.error("请设置url.list属性!")
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1;
      }
      var params = this.getQueryParams();//查询条件
      this.loading = true;
      let request = null
      const isNoPagnation = ['getDictByCode'].some(url => new RegExp(`${url}$`).test(this.url.list))
      if (isNoPagnation) {
        request = getAction
      } else {
        request = postAction
      }
      var that = this
      return request(this.url.list, params).then((res) => {
        if (res.success) {
          let {
            records = [],
            total
          } = res.result;
          that.ipagination.total = total
          that.dataSource = records
          that.moneyData = pick(res.result,'pagePriceAmount','totalAmount')
        }else{
          that.$message.warning(res.message)
        }
        that.loading = false;
      })
    },
  },
  created() {
    this.queryParam.doc = '订货单'

  },
  // beforeMount() {
  //   const draggingMap = {};
  //   this.columns.forEach((col) => {
  //     draggingMap[col.field] = col.width;
  //   });
  //   const draggingState = Vue.observable(draggingMap);
  //   const resizeableTitle = (h, props, children) => {
  //     let thDom = null;
  //     const { key, ...restProps } = props;
  //     console.log(props)
  //     let col;
  //     // 复选框筛选处理
  //     if (key === 'selection-column') {
  //       col = {};
  //     } else {
  //       col = this.columns.find((item) => {
  //         const k = item.field || item.key;
  //         return k === key;
  //       });
  //     }
  //     // 未设置宽度或者设置不可伸缩时不做伸缩处理
  //     if (!col.width || col.noStretch) {
  //       return <th {...restProps}>{children}</th>;
  //     }
  //     const onDrag = (x) => {
  //       draggingState[key] = 0;
  //       // 设置一个伸缩的最小宽度，防止页面错乱
  //       col.width = Math.max(x, col.minWidth || 30);
  //     };
  //     const onDragstop = () => {
  //       draggingState[key] = thDom.getBoundingClientRect().width;
  //     };
  //     return (
  //       <th
  //         {...restProps}
  //         v-ant-ref={(r) => (thDom = r)}
  //         width={col.width}
  //         class="resize-table-th"
  //       >
  //         {children}
  //         <vue-draggable-resizable
  //           key={col.key}
  //           class="table-draggable-handle"
  //           w={10}
  //           x={col.width||draggingState[key]}
  //           z={1}
  //           axis="x"
  //           draggable={true}
  //           resizable={false}
  //           onDragging={onDrag}
  //           onDragstop={onDragstop}
  //         />
  //       </th>
  //     );
  //   };
  //   this.components = {
  //     header: {
  //       cell: resizeableTitle,
  //     },
  //   };
  // },
  watch: {
    // pageHeight(val){
    //   // 为了避免频繁触发resize函数导致页面卡顿，使用定时器
    //   if(!this.timer){
    //     // 一旦监听到的screenWidth值改变，就将其重新赋给data里的screenWidth
    //     this.pageHeight = val
    //     this.timer = true
    //     let that = this
    //     setTimeout(function(){
    //       // 打印screenWidth变化的值
    //       console.log(that.pageHeight)
    //       that.timer = false
    //     },100)
    //   }
    // }
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  }
}
</script>

<style lang='less' scoped>
@import '~@assets/less/common.less';

/deep/ .ant-pagination {
  float: right;
}

///deep/ .resize-table-th {
//  position: relative;
//}
///deep/ .table-draggable-handle {
//  height: 100% !important;
//  bottom: 0;
//  left: auto !important;
//  right: -5px;
//  cursor: col-resize;
//  touch-action: none;
//}
.moreData {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  .moreData-box {
    display: flex;
    flex-direction: column;
    margin:0 8px;
  }
}
</style>